﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using RBS.Core.Extension;
using RBS.Core.Model;
using RBS.Core.Model.Hotel;
using RBS.Web.API.Models;
using System.Data.Objects.SqlClient;
namespace RBS.Web.API.Areas.Hotel.Controllers
{
    /// <summary>
    /// 酒店API
    /// </summary>
    public class SelectHotelController : ApiController
    {
        private ApiContext db = new ApiContext();
        private string  _webHotel = RBS.Common.ConfigHelper.GetConfigString("webHotel");
        /// <summary>
        /// 根据酒店ID获取酒店详细信息
        /// </summary>
        /// <param name="id">酒店ID</param>
        /// <returns></returns>
        public JsonData Get(int id)
        {
          
            var jsonData = new JsonData { Success = true };
            var clients = db.VHotel.FirstOrDefault(c => c.Id == id);
            jsonData.Data = clients;
            
            return jsonData; 
        } 
        /// <summary>
        /// test
        /// </summary>
        /// <returns></returns>
        public JsonDataList Get()
        {
            return Get("上海", "recommend", "浦东新区");
        } 
        /// <summary>
        /// 获取酒店列表
        /// </summary>
        /// <param name="city">当前城市</param>
        /// <param name="type">获取类型，recommend：推荐酒店，All：全部酒店</param>
        /// <param name="region">城市区域</param>
        /// <param name="category">菜系分类</param>
        /// <param name="keyword">关键字</param>
        /// <param name="sort">排序类型</param>
        /// <param name="page">当前页</param>
        /// <param name="limit">每页条数</param>
        /// <returns></returns> 
        public JsonDataList Get(string city, string type=null,string region = null, string category = null, string keyword = null, int sort=1, int page = 1, int limit = 5)
        {
            var jsonData = new JsonDataList {Success = true};
            try
            { 
                Expression<Func<V_Hotel, bool>> expression = PredicateExtensions.True<V_Hotel>(); 
                if (!string.IsNullOrEmpty(city))
                {
                    expression = expression.And(o=>o.City.Contains(city)).Or(o=>o.Province.Contains(city));
                }
                if (!string.IsNullOrEmpty(region))
                {
                    expression = expression.And(o => o.Region.Contains(region));
                }
                if (!string.IsNullOrEmpty(type) && type != "0")
                {
                    expression =  expression.And(o => o.IsRecommend == 1);
                }
                
                if (!string.IsNullOrEmpty(category))
                { 
                    expression = expression.And(o => o.Categories.Contains(category));
                }
                if (!string.IsNullOrEmpty(keyword))
                {
                    expression = expression.And(o => o.Name.Contains(keyword));
                } 
                //推荐酒店 
               var items = db.VHotel.Where(expression.Compile());

                if (!items.Any())
                {
                    jsonData.Data = null;
                    jsonData.Count = 0;
                    jsonData.Page = page;
                    jsonData.PageSize = limit;
                    jsonData.TotalPage = 0;
                    jsonData.Success = false;
                    jsonData.Error = "暂无数据";
                    return jsonData;
                } 
                    int total = items.Count();
                    double pageCount = Math.Ceiling((double) total/(double) limit);
                    int totalPage = (int) pageCount;
                    if (page > totalPage)
                    {
                        page = totalPage;
                        jsonData.Data = null;
                        jsonData.Count = 0;
                        jsonData.TotalCount = total;
                        jsonData.Page = page;
                        jsonData.PageSize = limit;
                        jsonData.TotalPage = totalPage;
                        jsonData.Success = false;
                        jsonData.Error = "最大页数为：" + totalPage + "页";
                        return jsonData;
                    }
                var itemlist = items; 
                switch (sort)
                {
                    case 1:
                       itemlist= itemlist.OrderByDescending(t => t.Id).Skip((page - 1)*limit).Take(limit).ToList();
                        break;
                    case 2:
                        itemlist = itemlist.OrderBy(t => t.Id).Skip((page - 1) * limit).Take(limit).ToList();
                        break;
                    case 3:
                        itemlist = itemlist.OrderByDescending(t => t.Renjun).Skip((page - 1) * limit).Take(limit).ToList();
                        break;
                }
             
                jsonData.Data = itemlist;
                jsonData.TotalCount = total;
                    jsonData.Count = total;
                    jsonData.Page = page;
                    jsonData.PageSize = limit;
                    jsonData.TotalPage = totalPage;
               
            }
            catch (Exception ex)
            {
                jsonData.Success = false;
                jsonData.Error = ex.Message;
            }

            return jsonData;
        }

        /// <summary>
        /// 查询酒店POST
        /// </summary>
        /// <param name="search">查询实体</param>
        /// <returns></returns>
        public JsonDataList Post([FromBody]HotelSearch search)
        {
            var jsonData = new JsonDataList { Success = true };
            try
            {
                var webHotel = RBS.Common.ConfigHelper.GetConfigString("webHotel");
                var expression = new StringBuilder();
                if (!string.IsNullOrEmpty(search.Category))
                {
                    expression.Append(" and Categories like '%" + search.Category + "%'");
                }
                if (!string.IsNullOrEmpty(search.City))
                {

                    expression.Append(" and (City like '%" + search.City + "%' or Province= '%" + search.City + "%')");
                }
                if (!string.IsNullOrEmpty(search.Region))
                {
                    expression.Append(" and Region ='" + search.Region + "'");
                }
               // expression = !string.IsNullOrEmpty(search.Type) ? expression.And(o => o.IsRecommend == 0) : expression.And(o => o.IsRecommend == 1); 

                if (!string.IsNullOrEmpty(search.Keyword))
                {
                    expression.Append(" and Name like '%" + search.Keyword + "%'");
                } 
                //推荐酒店  
              /*  switch (sort)
                {
                    case 1:
                        itemlist = itemlist.OrderByDescending(t => t.Id).Skip((page - 1) * limit).Take(limit).ToList();
                        break;
                    case 2:
                        itemlist = itemlist.OrderBy(t => t.Id).Skip((page - 1) * limit).Take(limit).ToList();
                        break;
                    case 3:
                        itemlist = itemlist.OrderByDescending(t => t.Renjun).Skip((page - 1) * limit).Take(limit).ToList();
                        break;
                }*/ 

                int total = 0;
                var modellist = new RBS.Core.BLL.Hotel.H_Hotels().GetList(search.clng, search.clat, 2000000, search.Limit,
                                                                          search.Page+1, expression.ToString(), " juli asc", out total); 

          
                double pageCount = Math.Ceiling((double)total / (double)search.Limit);
                int totalPage = (int)pageCount;
               /* if (search.Page > totalPage)
                { 
                         search.Page = totalPage;
                        jsonData.Data = null;
                        jsonData.Count = 0;
                        jsonData.TotalCount = total;
                        jsonData.Page = search.Page;
                        jsonData.PageSize = search.Limit;
                        jsonData.TotalPage = totalPage;
                        jsonData.Success = false;
                        jsonData.Error = "最大页数为：" + totalPage + "页";
                        return jsonData;
                 } */

                jsonData.Data = modellist;
                jsonData.TotalCount = total;
                jsonData.Count = total;
                jsonData.Page = search.Page;
                jsonData.PageSize = search.Limit;
                jsonData.TotalPage = totalPage;


            }
            catch (Exception ex)
            {

                
                jsonData.Success = false;
                jsonData.Error = ex.Message;
                RBS.Core.Logs.LogManager.WriteLog("selectHotel", ex.Message);  
            }

            return jsonData;
        } 
    }
     
    public class Hotel
    {
        public int Id { get; set; }
        public string Name { get; set; } 
        public string Address { get; set; }
        public string Telephone { get; set; }
        public string City { get; set; }
        public string Regions { get; set; }
        public string Categories { get; set; }
        public byte[] Img { get; set; }
        public decimal Renjun { get; set; }
        public double Pingfen { get; set; }
    }
   /// <summary>
   /// 查询实体
   /// </summary>
    public class HotelSearch
    { 
        /// <summary>
        /// 查询实体初始化
        /// </summary>
        public HotelSearch()
        {
            this.Sort = 1;
            this.Limit = 10;
            this.Page = 1;
        }

        public decimal clng { get; set; }
        public decimal clat { get; set; }
        public int km { get; set; }  
        /// <summary>
        /// 当前城市
        /// </summary>
        public  string City{ get; set; }
        /// <summary>
        /// 获取类型，recommend：推荐酒店，All：全部酒店
        /// </summary>
        public string Type{ get; set; }
        /// <summary>
        /// 城市区域
        /// </summary>
        public string Region{ get; set; } 
        /// <summary>
        /// 菜系分类
        /// </summary>
        public string Category{ get; set; }
        /// <summary>
        /// 关键字
        /// </summary>
        public string Keyword { get; set; }
        /// <summary>
        /// 排序类型
        /// </summary>
        public int Sort{ get; set; }
        /// <summary>
        /// 当前页
        /// </summary>
        public int Page{ get; set; }
        /// <summary>
        /// 每页条数
        /// </summary>
        public int Limit { get; set; }
         
    }
     
}
